package com.qiguliuxing.dts.wx.service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import com.qiguliuxing.dts.core.util.RedisKeyUtils;
import com.qiguliuxing.dts.wx.dao.CaptchaItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 缓存系统中的验证码
 */
@Component
public class CaptchaCodeManager {
	@Autowired
	private RedisTemplate redisTemplate;

	private static RedisTemplate staticRedisTemplate;

	//private static Map<String, CaptchaItem> captchaCodeCache = new HashMap<>();

	@PostConstruct
	public void init(){
		staticRedisTemplate = redisTemplate;
	}

	/**
	 * 添加到缓存
	 *
	 * @param phoneNumber
	 *            电话号码
	 * @param code
	 *            验证码
	 */
	public static boolean addToCache(String phoneNumber, String code) {

		// 已经发过验证码且验证码还未过期
//		if (captchaCodeCache.get(phoneNumber) != null) {
//			if (captchaCodeCache.get(phoneNumber).getExpireTime().isAfter(LocalDateTime.now())) {
//				return false;
//			} else {
//				// 存在但是已过期，删掉
//				captchaCodeCache.remove(phoneNumber);
//			}
//		}
		if (staticRedisTemplate.hasKey(RedisKeyUtils.getCaptchaCodeKey(phoneNumber))){
			return false;
		}

		CaptchaItem captchaItem = new CaptchaItem();
		captchaItem.setPhoneNumber(phoneNumber);
		captchaItem.setCode(code);
		// 有效期为3分钟
		captchaItem.setExpireTime(LocalDateTime.now().plusMinutes(3));

		//captchaCodeCache.put(phoneNumber, captchaItem);
		staticRedisTemplate.opsForValue().set(RedisKeyUtils.getCaptchaCodeKey(phoneNumber), captchaItem, 3, TimeUnit.MINUTES);
		return true;
	}

	/**
	 * 获取缓存的验证码
	 *
	 * @param phoneNumber
	 *            关联的电话号码
	 * @return 验证码
	 */
	public static String getCachedCaptcha(String phoneNumber) {
		// 没有这个电话记录
		//if (captchaCodeCache.get(phoneNumber) == null)
		if (staticRedisTemplate.hasKey(RedisKeyUtils.getCaptchaCodeKey(phoneNumber)) == null){
			return null;
		}

		// 有电话记录但是已经过期
//		if (captchaCodeCache.get(phoneNumber).getExpireTime().isBefore(LocalDateTime.now())) {
//			return null;
//		}
//		return captchaCodeCache.get(phoneNumber).getCode();
		CaptchaItem captchaItem = (CaptchaItem) staticRedisTemplate.opsForValue().get(RedisKeyUtils.getCaptchaCodeKey(phoneNumber));
		return captchaItem != null ? captchaItem.getCode() : null;
	}
}
